from django_filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from workflow.sers import *
from django.db import transaction
from django.utils.decorators import method_decorator


class TemplateViewSet(ModelViewSet):
    queryset = Templates.objects.all()
    serializer_class = TemplatesSer


class TempInstanceViewSet(ModelViewSet):
    queryset = TempInstance.objects.all()
    serializer_class = TempInstanceSer

    filter_fields = ('user',)  #  过滤按照用户


class FlowViewSet(ModelViewSet):
    queryset = Flow.objects.all()
    serializer_class = FlowSer


class FlowAPIView(APIView):

    @method_decorator(transaction.atomic)
    def post(self, request):
        # 提交工单和人员列表,
        # 1. instance  填好的表单, users , 审批人列表,  user  当前用户
        data = request.data
        instance = data.get('instance')
        users = data.get('users')
        user = request.user

        tempins = TempInstance(
            user=user,
            content=instance
        )

        tempins.save()
        seq = 1
        # raise Exception('123')
        for user_ in users:
            Flow.objects.create(
                user_id=user_.get('id'),
                instance=tempins,
                seq=seq
            )
            seq += 1

        return Response({'msg': '保存成功'})


class MyExamine(APIView):
    def get(self, request):
        # 获取一下, 需要我审批的工单
        user = request.user

        flows = Flow.objects.filter(user=user)

        # flows = > user, instance, status, comment, seq
        # 获取一个instance的集合, 给序列化器
        instances = []
        for flow in flows:
            instances.append(flow.instance)

        ser = TempInstanceSer(instances, many=True)

        return Response(ser.data)

    def post(self, request):
        # 更改审批状态
        # 用户  工单实例id,
        user = request.user
        instance_id = request.data.get('instance_id')
        status = request.data.get('status')
        comment = request.data.get('comment')

        flow = Flow.objects.get(user=user, instance_id=instance_id)
        flow.status = status
        flow.comment = comment
        flow.save()

        return Response({'msg': 'ok'})
